#!/bin/bash

# $@ 服务名 多个以空格分隔 如service-a service-b service-c
# 服务目录名 如business

# 获取服务目录名
function get_directory() {
  case "$1" in
  "service-a")
  echo gateway
  ;;
  "service-b")
  echo auth
  ;;
  "service-c")
  echo system
  ;;
  *)
  echo 404
  ;;
  esac
}

# 复制jar包
jar_directory="/usr/local/jars"
function copy_jar() {
  echo "copy $1 $2"
  cp -f "${jar_directory}/$1.jar" "./service/$2/jar/"
  mv "${jar_directory}/$1.jar" "${jar_directory}/$1_$3.jar"
}

# 部署
function deploy_service() {
  echo "deploy service $*"

  echo "remove $*"
  docker-compose rm -s "$*"

  echo "build $*"
  docker-compose build "$*"

  echo "start $*"
  docker-compose up -d "$*"
}

echo "deploy $*"

# 循环处理 复制jar包并获取合法服务名
service_name=""
date_str=$(date +%Y%m%d%H%M%S)
for s in "$@"
do
  f_name=$(get_directory "$s")
  if [ "$f_name" != "404" ]
  then
    copy_jar "$s" "$f_name" "$date_str"
    service_name="$service_name $s"
  fi
done

# 部署
if [ "$service_name" != "" ]
then
  deploy_service "$service_name"
  # 删除无用image和volume
  echo "clean image & volume"
  docker volume prune -f
  docker image prune -f
fi